package com.bjpowernode.handler;

import com.bjpowernode.service.impl.SomeServiceImpl;
import com.bjpowernode.util.ServiceTools;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MyInvocationHandler implements InvocationHandler {
    private Object target;

    public MyInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 通过代理对象执行时,会调用这个invocation
        Object res = null;
        // 执行目标类的方法,通过Method实现
        System.out.println("methodName = " + method.getName());
        if ("doSome".equals(method.getName())) {
            ServiceTools.doLog();
            res = method.invoke(target, args); //SomeServiceImpl.doOther() or doSome()
            // 目标方法执行的结果
            ServiceTools.doTrans();
        } else {
            res = method.invoke(target, args); //SomeServiceImpl.doOther() or doSome()
        }
        return res;
    }
}
